package com.example.mypplication.aicoze

import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import okhttp3.*
import java.io.IOException
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaTypeOrNull

// API配置
const val API_URL = "https://api.coze.cn/v3/chat"
const val RETRIEVE_URL = "https://api.coze.cn/v3/chat/retrieve"
const val PAT_TOKEN = "sat_V4EBCxET6gWqra1xpMByqsOEgje9M2aE24TcR2t4QBqQiXXvn5qRIXDRZq27lqzW"
const val BOT_ID = "7550317080500240423"
const val USER_ID = "user_1234561"

// 数据类定义
data class ChatRequest(
    val bot_id: String,
    val user_id: String,
    val stream: Boolean,
    val auto_save_history: Boolean,
    val additional_messages: List<AdditionalMessage>
)

data class AdditionalMessage(
    val role: String,
    val content: String,
    val content_type: String
)

data class ChatResponse(
    val code: Int,
    val msg: String,
    val data: ChatData
)

data class ChatData(
    val id: String,
    val conversation_id: String,
    val status: String,
    @SerializedName("messages") val messages: List<Message>? = null
)

data class Message(
    @SerializedName("role") val role: String,
    @SerializedName("content") val content: String
)

data class RetrieveResponse(
    val code: Int,
    val data: RetrieveData
)

// 修复1：创建专门的轮询响应数据结构
data class RetrieveData(
    val id: String,
    val conversation_id: String,
    val status: String,
    @SerializedName("messages") val messages: List<Message>? = null
)

// OkHttp客户端
val client = OkHttpClient()
val gson = Gson()

// 发送消息函数
fun sendMessage(message: String, callback: (String) -> Unit) {
    val requestBody = ChatRequest(
        bot_id = BOT_ID,
        user_id = USER_ID,
        stream = false,
        auto_save_history = true,
        additional_messages = listOf(
            AdditionalMessage(
                role = "user",
                content = message,
                content_type = "text"
            )
        )
    )

    val jsonBody = gson.toJson(requestBody)
    val body = RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), jsonBody)

    val request = Request.Builder()
        .url(API_URL)
        .addHeader("Authorization", "Bearer $PAT_TOKEN")
        .addHeader("Content-Type", "application/json")
        .post(body)
        .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            callback("请求失败: ${e.message}")
        }

        override fun onResponse(call: Call, response: Response) {
            val responseBody = response.body?.string()
            println("API响应: $responseBody")

            try {
                val chatResponse = gson.fromJson(responseBody, ChatResponse::class.java)

                if (chatResponse.code != 0) {
                    callback("API错误: ${chatResponse.msg}")
                    return
                }

                // 轮询获取结果
                runBlocking {
                    pollResult(chatResponse.data.conversation_id, chatResponse.data.id, callback)
                }
            } catch (e: Exception) {
                callback("解析响应失败: ${e.message}")
            }
        }
    })
}

// 轮询结果函数 - 完全重写
suspend fun pollResult(
    conversationId: String,
    chatId: String,
    callback: (String) -> Unit
) {
    repeat(20) { attempt ->
        delay(2000) // 减少等待时间到2秒
        println("轮询第${attempt+1}次: conversation_id=$conversationId, chat_id=$chatId")

        // 修复：添加查询参数来获取消息
        val url = RETRIEVE_URL.toHttpUrlOrNull()!!.newBuilder()
            .addQueryParameter("conversation_id", conversationId)
            .addQueryParameter("chat_id", chatId)
            .addQueryParameter("include_messages", "true") // 关键参数：包含消息
            .build()

        val request = Request.Builder()
            .url(url)
            .addHeader("Authorization", "Bearer $PAT_TOKEN")
            .build()

        try {
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string()
            println("轮询响应: $responseBody")

            val retrieveResponse = gson.fromJson(responseBody, RetrieveResponse::class.java)

            if (retrieveResponse.code == 0) {
                when (retrieveResponse.data.status) {
                    "completed" -> {
                        // 修复2：直接从轮询响应中获取消息
                        val messages = retrieveResponse.data.messages

                        if (messages != null && messages.isNotEmpty()) {
                            // 查找assistant角色的消息
                            val assistantMessage = messages.firstOrNull {
                                it.role == "assistant" && it.content.isNotBlank()
                            }

                            if (assistantMessage != null) {
                                callback(assistantMessage.content)
                                return
                            } else {
                                // 如果没有找到assistant消息，返回第一条非空消息
                                val firstValidMessage = messages.firstOrNull { it.content.isNotBlank() }
                                if (firstValidMessage != null) {
                                    callback(firstValidMessage.content)
                                    return
                                }
                            }
                        }

                        // 如果到这里还没有返回，说明没有找到有效消息
                        callback("对话已完成，但未找到有效回复内容")
                        return
                    }
                    "failed" -> {
                        callback("智能体处理失败")
                        return
                    }
                    "in_progress" -> {
                        // 继续轮询
                    }
                    else -> {
                        // 其他状态继续轮询
                    }
                }
            } else {
                callback("轮询API错误: ${retrieveResponse.code} - ${retrieveResponse.data}")
                return
            }
        } catch (e: Exception) {
            println("轮询异常: ${e.message}")
            if (attempt == 19) { // 最后一次尝试
                callback("轮询过程中发生异常: ${e.message}")
                return
            }
        }
    }
    callback("请求超时")
}

// 使用示例
fun main() {
    sendMessage("你好") { result ->
        println("智能体回复: $result")
    }
    // 保持程序运行
    Thread.sleep(60000)
}